<!-- 角色管理 -->
<template>
  <div class="userManage sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="手机号:">
              <el-input v-model="query.phone" placeholder="请输入手机号" clearable/>
            </el-form-item>
            <el-form-item label="邮箱:">
              <el-input v-model="query.email" placeholder="请输入邮箱" clearable/>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="用户数据" icon="UserFilled" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-table ref="table" :data="dataList" max-height="493" border>
          <el-table-column label="用户编号" prop="userId" align="center"></el-table-column>
          <el-table-column label="用户名称" prop="name" align="center"></el-table-column>
          <el-table-column label="用户角色" prop="roleNames" header-align="center"></el-table-column>
          <el-table-column label="登录账号" prop="loginAccount" align="center"></el-table-column>
          <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
          <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
          <el-table-column label="性别" prop="sex" align="center">
            <template #default="{row}">
              <el-tag :type="row.sex === 1 ? 'success' : 'danger'">{{ row.sex === 1 ? '男' : '女' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="enableStatus" header-align="center" align="center">
            <template #default="{row}">
              <el-switch 
                v-model="row.enableStatus" 
                :inactive-text="row.enableStatus ? '启用' : '禁用'" 
                :active-value="1"
                :inactive-value="0"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" 
                disabled/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row.userId)">修改</el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.userId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" :title="form.userId ? '编辑' : '新增'" top="10vh" width="23%" center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default" label-width="85px">
        <el-form-item label="账号:" prop="loginAccount" required>
          <el-input v-model="form.loginAccount" placeholder="请输入登录账号" clearable/>
        </el-form-item>
        <el-form-item label="姓名:" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入姓名" clearable/>
        </el-form-item>
        <el-form-item label="手机号:" prop="phone" required>
          <el-input v-model="form.phone" placeholder="请输入手机号" clearable/>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email" required>
          <el-input v-model="form.email" placeholder="请输入邮箱" clearable/>
        </el-form-item>
        <el-form-item v-if="!form.userId" label="密码:" prop="passwords" required>
          <el-input v-model="form.passwords" type="password" placeholder="请输入密码" clearable show-password/>
        </el-form-item>
        <el-form-item label="角色:" prop="roleIdList" required>
          <el-select v-model="form.roleIdList" placeholder="请选择角色" multiple clearable>
            <el-option v-for="item in roles" :key="item.roleId" :label="item.name" :value="item.roleId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态:" prop="enableStatus">
          <el-radio-group v-model="form.enableStatus">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="userManage">
  import { cudUserApi, getUserPagesApi, getRoleApi, getUserInfoApi } from '@/api/api'
  import { regexAccount, regexPhone, regexMail, regexPassword } from '@/utils/utils'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  // 获取form表单的ref
  const formRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    query: {
      email: '',
      phone: '',
      userType: '1',
      current: 1,
      size: 20,
      total: 0
    },
    roles: [],
    dataList: [],
    form: {
      userId: '',
      name: '',
      loginAccount: '',
      phone: '',
      email: '',
      password: '',
      roleIdList: [],
      sex: 1,
      enableStatus: 1,
      userType: 1,
      passwords: ''
    },
    rules: {
      name: [{ required: true, message: '请输入姓名', trigger: ['blur', 'change'] }],
      loginAccount: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入登陆账号'))
            } else {
              if(!regexAccount(value)) {
                callback(new Error('账号为4-16个字符，不包含特殊字符'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      phone: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入手机号'))
            } else {
              if(!regexPhone(value)) {
                callback(new Error('手机号必须是11位，请重新输入'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      email: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入邮箱'))
            } else {
              if(!regexMail(value)) {
                callback(new Error('电子邮箱格式不对，请重新输入'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      passwords: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入密码'))
            } else {
              if(!regexPassword(value)) {
                callback(new Error('密码为8-20个字符，包含字母，数字，字符,'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      roleIdList: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(value.length === 0) {
              callback(new Error('请选择角色'))
            } else {
              callback()
            }
          } 
        }
      ]
    }
  })

  let {loading, show, query, roles, dataList, form, rules} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getUserPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 重置查询
  function resetSearch() {
    currentData.query.email = ''
    currentData.query.phone = ''
    load(1)
  }

  // 获取角色下拉数据
  function getRoles() {
    getRoleApi({
      roleType: '2'
    }).then(res => {
      if(res.code === '200') {
        currentData.roles = res.data
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 新增或编辑
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.userId ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.userId ? '修改' : '新增'}`)
          if(!currentData.form.userId) {
            currentData.form.password = currentThis.$md5(currentData.form.passwords)
          }
          cudUserApi(`${currentData.form.userId ? 'update' : 'save'}`, currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              if(currentData.form.userId) {
                load(currentData.query.current)
              } else {
                load(1)
              }
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 修改前弹窗
  function toUpdate(userId) {
    // 根据用户id查询用户信息
    getUserInfoApi(userId).then(res => {
      if(res.code === '200') {
        currentData.form = res.data
        currentData.show = true
      } else {
        currentThis.$message.error('获取用户信息失败')
      }
    })
  }

  // 删除
  function doDelete(userId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('删除中，请耐心等待')
      cudUserApi('delete', { id: userId }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 新增编辑弹窗重置数据
  function resetForm() {
    currentData.form = {
      userId: '',
      name: '',
      loginAccount: '',
      phone: '',
      email: '',
      password: '',
      roleIdList: [],
      sex: 1,
      enableStatus: 1,
      userType: 1,
      passwords: ''
    }
    formRef.value.resetFields()
  }

  // 分页每页显示条数改变执行
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
    getRoles()
  })
</script>

<style lang="less" scoped>
.userManage{
  :deep(.el-dialog){
    .el-input, .el-textarea{
      width: 300px;
    }
  }
  :deep(.el-switch.is-disabled){
    opacity: 1;
    .el-switch__label.is-active{
      color: #303133;
    }
  }
}
</style>